<template>
  <div class="fanqie-admin">
    <!-- 管理员页面顶部导航 -->
    <div class="admin-header">
      <h1>番茄读书管理</h1>
      <div class="admin-actions">
        <template v-if="isLoggedIn">
          <span class="welcome">欢迎, {{ username }}!</span>
          <el-button type="primary" link @click="logout">登出</el-button>
        </template>
        <template v-else>
          <router-link to="/login">
            <el-button type="primary" link>登录</el-button>
          </router-link>
          <router-link to="/register">
            <el-button type="primary" link>注册</el-button>
          </router-link>
        </template>
        <el-button v-if="isLoggedIn" type="primary" @click="showAddForm">添加小说</el-button>
      </div>
    </div>

    <!-- 未登录提示 -->
    <div v-if="!isLoggedIn" class="login-prompt">
      <p v-if="!username">请登录以访问管理功能</p>
      <p v-else>你的账号等级太低，不属于管理员等级</p>
      <router-link to="/login">
        <el-button type="primary">立即登录</el-button>
      </router-link>
    </div>

    <!-- 已登录内容 -->
    <template v-else>
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input v-model="searchForm.query" placeholder="请输入书名或作者" clearable />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 150px;">
              <el-option label="全部" value="" />
              <el-option label="玄幻" value="玄幻" />
              <el-option label="修真" value="修真" />
              <el-option label="都市" value="都市" />
              <el-option label="历史" value="历史" />
              <el-option label="科幻" value="科幻" />
              <el-option label="游戏" value="游戏" />
              <el-option label="竞技" value="竞技" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchBooks">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <!-- 使用计算属性实现分页功能 -->
        <el-table :data="paginatedBooks" border stripe v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="图片" width="100">
            <template #default="scope">
              <div class="image-cell">
                <el-image 
                  :src="getImageUrl(scope.row.image)" 
                  class="book-cover-mini" 
                  fit="cover"
                  :preview-src-list="scope.row.image ? [scope.row.image] : []"
                  hide-on-click-modal
                  :alt="scope.row.title"
                  loading="lazy"
                  @error="handleImageError"
                >
                  <template #placeholder>
                    <div class="image-slot">
                      加载中...
                    </div>
                  </template>
                  <template #error>
                    <div class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                      <div style="font-size: 10px; margin-top: 2px;">加载失败</div>
                    </div>
                  </template>
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="书名" min-width="150" />
          <el-table-column prop="author" label="作者" width="120" />
          <el-table-column prop="category" label="分类" width="100">
            <!-- 添加默认值处理，避免空值显示异常 -->
            <template #default="scope">
              {{ scope.row.category || '未知' }}
            </template>
          </el-table-column>
          <el-table-column prop="publisher" label="出版社" width="150" />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              ¥{{ Math.floor(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="showEditForm(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteBook(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next, jumper"
          />
        </div>
      </div>
    </template>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" @close="handleDialogClose">
      <el-form :model="currentBook" :rules="bookRules" ref="bookFormRef" label-width="80px">
        <el-form-item label="书名" prop="title">
          <el-input v-model="currentBook.title" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="currentBook.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="currentBook.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="玄幻" value="玄幻" />
            <el-option label="修真" value="修真" />
            <el-option label="都市" value="都市" />
            <el-option label="历史" value="历史" />
            <el-option label="科幻" value="科幻" />
            <el-option label="游戏" value="游戏" />
            <el-option label="竞技" value="竞技" />
          </el-select>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="currentBook.publisher" placeholder="请输入出版社" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="currentBook.price" :min="0" :precision="0" :step="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="currentBook.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <el-input v-model="currentBook.image" placeholder="请输入封面图片URL" />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            class="upload-demo"
            action="/api/fanqie/upload"
            :auto-upload="true"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-progress="handleUploadProgress"
            :on-change="handleFileChange"
            :show-file-list="false"
            :headers="uploadHeaders"
            name="image"
            :accept="'.jpg,.jpeg,.png,.gif'"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请选择jpg、jpeg、png或gif格式的图片文件，文件大小不超过2MB
              </div>
            </template>
          </el-upload>
          <div v-if="uploadErrorMessage" class="upload-error-message">
            {{ uploadErrorMessage }}
          </div>
        </el-form-item>
        <el-form-item v-if="currentBook.image">
          <el-image
            style="width: 100px; height: 100px"
            :src="currentBook.image"
            fit="cover"
            :preview-src-list="[currentBook.image]"
            hide-on-click-modal
          >
            <template #error>
              <div class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveBook">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import defaultBookCover from '../assets/tp1.jpg'

export default defineComponent({
  name: 'FanqieAdmin',
  setup() {
    // 数据相关
    const books = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const dialogTitle = ref('添加小说')
    const currentPage = ref(1)
    const pageSize = ref(3) // 修改为每页显示3个项目
    const total = ref(0)
    const isLoggedIn = ref(false)
    const username = ref('')
    
    // 表单引用
    const bookFormRef = ref()
    
    // 搜索表单
    const searchForm = reactive({
      query: '',
      category: ''
    })
    
    // 当前编辑的小说
    const currentBook = reactive({
      id: null,
      title: '',
      author: '',
      category: '',
      publisher: '',
      price: 0,
      description: '',
      image: ''
    })
    
    // 表单验证规则
    const bookRules = {
      title: [
        { required: true, message: '请输入书名', trigger: 'blur' }
      ],
      author: [
        { required: true, message: '请输入作者', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      publisher: [
        { required: true, message: '请输入出版社', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入描述', trigger: 'blur' }
      ]
    }
    
    // 获取书籍列表
    const fetchBooks = async () => {
      loading.value = true
      try {
        // 使用正确的API端点
        const response = await fetch('/api/fanqie/list')
        const result = await response.json()
        
        if (result.success) {
          books.value = result.data
          total.value = result.data.length
          console.log('获取到的书籍数据:', result.data);
          // 检查第一条数据的图片URL
          if (result.data && result.data.length > 0) {
            console.log('第一条数据的图片URL:', result.data[0].image);
          }
        } else {
          ElMessage.error(result.message || '获取书籍列表失败')
        }
      } catch (error) {
        console.error('获取书籍列表失败:', error)
        ElMessage.error('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索书籍
    const searchBooks = async () => {
      loading.value = true
      try {
        // 构建搜索参数
        let url = '/api/fanqie/search'  // 修改为正确的搜索API端点
        
        const params = []
        if (searchForm.query) {
          params.push(`q=${encodeURIComponent(searchForm.query)}`)
        }
        if (searchForm.category) {
          params.push(`category=${encodeURIComponent(searchForm.category)}`)
        }
        
        if (params.length > 0) {
          url += `?${params.join('&')}`
        } else {
          url = '/api/fanqie/list'
        }
        
        const response = await fetch(url)
        const result = await response.json()
        
        if (result.success) {
          books.value = result.data
          total.value = result.data.length
        } else {
          ElMessage.error(result.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索书籍失败:', error)
        ElMessage.error('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.query = ''
      searchForm.category = ''
      fetchBooks()
    }
    
    // 显示添加表单
    const showAddForm = () => {
      isEdit.value = false
      dialogTitle.value = '添加小说'
      // 重置表单，确保移除 isbn 字段
      Object.assign(currentBook, {
        id: null,
        title: '',
        author: '',
        category: '',
        publisher: '',
        price: 0,
        description: '',
        image: ''
      })
      dialogVisible.value = true
    }
    
    // 显示编辑表单
    const showEditForm = (book) => {
      isEdit.value = true
      dialogTitle.value = '编辑小说'
      Object.assign(currentBook, book)
      dialogVisible.value = true
    }
    
    // 保存书籍（添加或更新）
    const saveBook = async () => {
      if (!bookFormRef.value) return
      
      await bookFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 使用正确的API端点
            let url = '/api/fanqie'
            let method = 'POST'
            
            if (isEdit.value) {
              url += `/${currentBook.id}`
              method = 'PUT'
            }
            
            const response = await fetch(url, {
              method,
              headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
              },
              body: JSON.stringify({
                title: currentBook.title,
                author: currentBook.author,
                category: currentBook.category,
                publisher: currentBook.publisher,
                price: currentBook.price,
                description: currentBook.description,
                image: currentBook.image
              })
            })
            
            // 检查响应状态
            if (!response.ok) {
              const errorText = await response.text();
              throw new Error(`HTTP ${response.status}: ${errorText.substring(0, 200)}...`)
            }
            
            // 检查响应类型
            const contentType = response.headers.get('content-type')
            if (!contentType || !contentType.includes('application/json')) {
              const text = await response.text()
              throw new Error(`服务器返回非JSON响应: ${text.substring(0, 100)}...`)
            }
            
            const result = await response.json()
            
            if (result.success) {
              ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
              dialogVisible.value = false
              fetchBooks() // 重新获取列表
            } else {
              ElMessage.error(result.message || (isEdit.value ? '更新失败' : '添加失败'))
              if (result.errors) {
                Object.keys(result.errors).forEach(key => {
                  ElMessage.error(`${key}: ${result.errors[key][0]}`)
                })
              }
            }
          } catch (error) {
            console.error('保存书籍失败:', error)
            ElMessage.error(`网络错误: ${error.message}`)
          }
        }
      })
    }
    
    // 删除书籍
    const deleteBook = (id) => {
      ElMessageBox.confirm('确认删除这本书吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await fetch(`/api/fanqie/${id}`, {
            method: 'DELETE',
            headers: {
              'X-Requested-With': 'XMLHttpRequest'
            }
          })
          
          // 检查响应状态
          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP ${response.status}: ${errorText.substring(0, 200)}...`)
          }
          
          // 检查响应类型
          const contentType = response.headers.get('content-type')
          let result
          if (contentType && contentType.includes('application/json')) {
            result = await response.json()
          } else {
            const text = await response.text()
            throw new Error(`服务器返回非JSON响应: ${text.substring(0, 100)}...`)
          }
          
          if (result.success) {
            ElMessage.success('删除成功')
            fetchBooks() // 重新获取列表
          } else {
            ElMessage.error(result.message || '删除失败')
          }
        } catch (error) {
          console.error('删除书籍失败:', error)
          ElMessage.error(`网络错误: ${error.message}`)
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 处理对话框关闭
    const handleDialogClose = () => {
      bookFormRef.value?.resetFields()
    }
    
    // 计算分页后的书籍数据
    const paginatedBooks = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return books.value.slice(start, end)
    })
    
    // 处理分页变化
    const handlePageChange = (page) => {
      currentPage.value = page
      // 分页逻辑已通过computed属性实现
    }
    
    // 上传请求头
    const uploadHeaders = {
      'X-Requested-With': 'XMLHttpRequest'
    }
    
    // 上传错误消息
    const uploadErrorMessage = ref('')
    
    // 文件变化处理
    const handleFileChange = (file, fileList) => {
      // 清除之前的错误消息
      uploadErrorMessage.value = ''
      
      // 输出文件详细信息用于调试
      console.log('选择的文件:', file)
      if (file && file.raw) {
        console.log('文件名:', file.name)
        console.log('文件类型:', file.type)
        console.log('文件大小:', file.size)
        console.log('文件原始对象:', file.raw)
      }
    }
    
    // 上传前检查
    const beforeUpload = (file) => {
      // 清除之前的错误消息
      uploadErrorMessage.value = ''
      
      console.log('准备上传的文件:', file)
      console.log('文件名:', file.name)
      console.log('文件类型:', file.type)
      console.log('文件大小:', file.size)
      
      // 即使type为undefined，我们也允许上传，让后端进行验证
      // 只检查文件大小
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isLt2M) {
        const errorMsg = '图片大小不能超过 2MB！';
        ElMessage.error(errorMsg);
        uploadErrorMessage.value = errorMsg;
        return false;
      }
      
      // 如果文件类型可用，进行额外检查
      if (file.type) {
        const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
        if (!isValidType) {
          const errorMsg = `图片格式不正确，当前文件类型为: ${file.type}，请上传 JPG、PNG 或 GIF 格式的图片！`;
          ElMessage.error(errorMsg);
          uploadErrorMessage.value = errorMsg;
          return false;
        }
      }
      
      return true;
    }
    
    // 上传成功处理
    const handleUploadSuccess = (response, uploadFile) => {
      console.log('上传成功响应:', response);
      if (response && response.success) {
        if (response.data && response.data.url) {
          currentBook.image = response.data.url
          ElMessage.success('图片上传成功')
          // 清除错误消息
          uploadErrorMessage.value = ''
        } else {
          const errorMsg = response.message || '服务器返回数据格式不正确'
          ElMessage.error(errorMsg)
          uploadErrorMessage.value = errorMsg
        }
      } else {
        const errorMsg = response?.message || '图片上传失败'
        ElMessage.error(errorMsg)
        uploadErrorMessage.value = errorMsg
      }
    }
    
    // 上传失败处理
    const handleUploadError = (error, uploadFile, uploadFiles) => {
      console.error('上传错误:', error);
      let errorMessage = '图片上传失败，请重试';
      
      // 尝试解析错误响应
      if (error && error.response) {
        if (typeof error.response === 'string') {
          try {
            const errorObj = JSON.parse(error.response);
            errorMessage = formatUploadErrorMessage(errorObj);
          } catch (e) {
            errorMessage = error.response.substring(0, 100) + '...';
          }
        } else if (error.response.message) {
          errorMessage = formatUploadErrorMessage(error.response);
        }
      }
      
      ElMessage.error(errorMessage);
      uploadErrorMessage.value = errorMessage;
    }
    
    // 格式化上传错误消息
    const formatUploadErrorMessage = (errorObj) => {
      let message = errorObj.message || '图片上传失败';
      
      // 处理验证错误
      if (errorObj.errors) {
        const errorKeys = Object.keys(errorObj.errors);
        if (errorKeys.length > 0) {
          const firstErrorKey = errorKeys[0];
          const firstErrorMessages = errorObj.errors[firstErrorKey];
          
          if (firstErrorMessages && firstErrorMessages.length > 0) {
            // 特别处理图片类型错误
            if (firstErrorKey === 'image') {
              if (firstErrorMessages[0].includes('jpeg') && firstErrorMessages[0].includes('png')) {
                message = '请选择有效的图片文件（jpg、jpeg、png、gif格式）';
              } else {
                message = '图片文件不符合要求：' + firstErrorMessages[0];
              }
            } else {
              message = firstErrorMessages[0];
            }
          }
        }
      }
      
      return message;
    }
    
    // 上传进度处理
    const handleUploadProgress = (event, uploadFile, uploadFiles) => {
      // 可以在这里添加进度条显示等逻辑
      console.log('上传进度:', event);
    }
    
    // 获取图片URL的处理函数
    const getImageUrl = (imageUrl) => {
      console.log('原始图片URL:', imageUrl);
      
      // 如果没有图片URL，返回默认图片
      if (!imageUrl) {
        console.log('使用默认图片:', defaultBookCover);
        return defaultBookCover;
      }
      
      // 如果是完整URL，直接返回
      if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        console.log('使用完整URL:', imageUrl);
        return imageUrl;
      }
      
      // 如果是绝对路径（以/开头），需要添加基础路径
      if (imageUrl.startsWith('/')) {
        // Laravel存储的图片在 /storage 路径下
        const fullUrl = imageUrl;
        console.log('使用绝对路径:', fullUrl);
        return fullUrl;
      }
      
      // 其他情况直接返回
      console.log('使用其他格式URL:', imageUrl);
      return imageUrl;
    }
    
    // 图片加载错误处理
    const handleImageError = (e) => {
      console.log('图片加载失败:', e);
      console.log('失败的图片URL:', e.target?.src);
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      checkLoginStatus()
      if (isLoggedIn.value) {
        fetchBooks()
      }
    })
    
    // 检查登录状态
    const checkLoginStatus = () => {
      const user = localStorage.getItem('user')
      if (user) {
        const userData = JSON.parse(user)
        // 检查用户类型是否为管理员
        if (userData.user_type === 'admin') {
          isLoggedIn.value = true
          username.value = userData.name || userData.username || '管理员'
        } else {
          // 用户不是管理员，显示提示信息
          isLoggedIn.value = false
          username.value = ''
          ElMessage.error('你的账号等级太低，不属于管理员等级')
        }
      } else {
        isLoggedIn.value = false
        username.value = ''
      }
    }
    
    // 登出功能
    const logout = () => {
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除用户信息
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        localStorage.removeItem('rememberedLogin') // 清除记住的登录信息
        isLoggedIn.value = false
        username.value = ''
        books.value = []
        ElMessage.success('已退出登录')
      }).catch(() => {
        // 用户取消登出
      })
    }
    
    return {
      // 数据
      books,
      paginatedBooks, // 添加分页后的书籍数据
      loading,
      dialogVisible,
      dialogTitle,
      currentPage,
      pageSize,
      total,
      searchForm,
      currentBook,
      bookRules,
      uploadErrorMessage,
      defaultBookCover,
      isLoggedIn,
      username,
      
      // 引用
      bookFormRef,
      
      // 方法
      searchBooks,
      resetSearch,
      showAddForm,
      showEditForm,
      saveBook,
      deleteBook,
      handleDialogClose,
      handlePageChange,
      handleUploadSuccess,
      handleUploadError,
      handleUploadProgress,
      handleFileChange,
      uploadHeaders,
      formatUploadErrorMessage,
      beforeUpload,
      getImageUrl,
      handleImageError,
      logout
    }
  }
})
</script>

<style scoped>
.fanqie-admin {
  padding: 20px;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.admin-header h1 {
  margin: 0;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.table-section {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-demo {
  width: 100%;
}

.el-image {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.upload-error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.book-info {
  display: flex;
  align-items: center;
}

.book-title {
  font-weight: 500;
}

.image-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.book-cover-mini {
  width: 60px;
  height: 80px;
  object-fit: cover;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.login-prompt {
  text-align: center;
  padding: 50px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-prompt p {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}
</style>
